package com.base.themvx.utils

import com.base.themvx.defNonSyncLazy

/**
 ******************(^_^)***********************<br>
 * Author: fee(QQ/WeiXin:1176610771)<br>
 * Time: 16:39<br>
 * <P>DESC:
 * 仿 EventBus
 * </p>
 * ******************(^_^)***********************
 */
class EventRouter private constructor() {

    companion object Helper {

        private val sEventBus by defNonSyncLazy {
            EventRouter()
        }

        fun register(aEventRouter: IEventBusRouter) {
            sEventBus.registerRouter(aEventRouter)
        }

        fun unregister(aEventRouter: IEventBusRouter) {
            sEventBus.unregisterRouter(aEventRouter)
        }

        fun routeEvent(eventType: String, eventExtraData: Any? = null) {
            if (eventType.isBlank()) {
                return
            }
            val aEventData = EventRouteData()
            aEventData.eventType = eventType
            aEventData.extraData = eventExtraData
            sEventBus.onEventRoute(aEventData)
        }
    }

    private val mEventRouters by defNonSyncLazy {
        mutableListOf<IEventBusRouter>()
    }

    fun registerRouter(aEventRouter: IEventBusRouter) {
        val theList = mEventRouters
        if (theList.contains(aEventRouter)) {
            return
        }
        theList.add(aEventRouter)
    }

    fun unregisterRouter(aEventRouter: IEventBusRouter) {
        val theList = mEventRouters
        if (theList.contains(aEventRouter)) {
            theList.remove(aEventRouter)
        }
    }


    private fun onEventRoute(aEventRouteData: EventRouteData) {
        val theList = mEventRouters
        theList.forEach {
            if (it.onEventRoute(aEventRouteData)) {
                return
            }
        }
    }
}

class EventRouteData {

    var eventType: String = ""
    var extraData: Any? = null

}

interface IEventBusRouter {

    /**
     * 事件路由
     * @param theEventRouteData 具体的事件数据
     */
    fun onEventRoute(theEventRouteData: EventRouteData): Boolean

}